/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "node/util/error.h"

#include <cstdio>
#include <WinSock2.h>

namespace node {
    namespace util {
        namespace error {

            static const char *GetErrorMessage(int code, char* dest, ::std::size_t size)
            {
                char *s = NULL;
                FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER 
                    | FORMAT_MESSAGE_FROM_SYSTEM 
                    | FORMAT_MESSAGE_IGNORE_INSERTS,
                    NULL, code,
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    (LPSTR)&s, 0, NULL);
                _snprintf_s(dest, size, _TRUNCATE, "%s", s);
                LocalFree(s);
                return dest;
            }

            int errcode(bool neterr /*= false*/)
            {
                return int(neterr ? WSAGetLastError() : GetLastError());
            }

            const char *errstr(int ecode, char* dest, ::std::size_t size)
            {
                return GetErrorMessage(ecode, dest, size);
            }

            const char *errstr(int ecode, ::std::string& dest)
            {
                char message[0x200];
                dest = GetErrorMessage(ecode, message, sizeof(message));
                return dest.c_str();
            }

        }
    }
}